package com.finger.userservice.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.finger.commonutil.exception.YyghException;
import com.finger.commonutil.helper.JwtHelper;
import com.finger.modelservice.enums.AuthStatusEnum;
import com.finger.modelservice.model.user.Patient;
import com.finger.modelservice.model.user.UserInfo;
import com.finger.modelservice.result.ResultCodeEnum;
import com.finger.modelservice.vo.user.LoginVo;
import com.finger.modelservice.vo.user.UserAuthVo;
import com.finger.modelservice.vo.user.UserInfoQueryVo;
import com.finger.userservice.mapper.UserInfoMapper;
import com.finger.userservice.service.PatientService;
import com.finger.userservice.service.UserInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

@Service
public class UserInfoServiceImpl extends ServiceImpl<UserInfoMapper, UserInfo> implements UserInfoService{

    @Autowired
    private PatientService patientService;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @Override
    public void lock(Integer status, String userId) {

        if(status == 1 || status == 0){
            UserInfo userInfo = new UserInfo();
            userInfo.setStatus(status);
            userInfo.setId(userId);
            baseMapper.updateById(userInfo);
        }
    }

    @Override
    public Map<String, Object> login(LoginVo loginVo) {
        String phone = loginVo.getPhone();
        String code = loginVo.getCode();
        // 判断前端传过来的手机号和验证码是否为空
        if(StringUtils.isEmpty(phone) || StringUtils.isEmpty(code) || phone.length()!=11){
            throw new YyghException(ResultCodeEnum.PARAM_ERROR);
        }

        String redisCode = redisTemplate.opsForValue().get(phone);

        // 判断缓存中的验证码是否为空，并且前端传过来的验证码和缓存中的是否相同
        if(StringUtils.isEmpty(redisCode) || !Objects.equals(code,redisCode)){
            throw new YyghException(ResultCodeEnum.CODE_ERROR);
        }

        String openid = loginVo.getOpenid();
        UserInfo userInfo = baseMapper.selectOne(new QueryWrapper<UserInfo>().eq("phone", phone));;
        // 能进这个if的数据库肯定有微信信息
        // TODO
        if(!StringUtils.isEmpty(openid)){

            // 根据微信id获取用户信息
            UserInfo userInfoWx = baseMapper.selectOne(new QueryWrapper<UserInfo>().eq("openid", openid));

            // 当前手机号数据库里边已经有了
            if(userInfo==null){
                userInfoWx.setPhone(phone);
                baseMapper.updateById(userInfoWx);
                userInfo = userInfoWx;
            }else{
                userInfo.setNickName(userInfoWx.getNickName());
                userInfo.setOpenid(userInfoWx.getOpenid());
                baseMapper.updateById(userInfo);
            }

        }else{

            if(Objects.isNull(userInfo)){
                userInfo = new UserInfo();
                userInfo.setPhone(phone);
                userInfo.setStatus(1);
                userInfo.setName("");
                userInfo.setNickName("");
                baseMapper.insert(userInfo);
            }
        }

        if(userInfo.getStatus()==0){
            throw new YyghException(ResultCodeEnum.LOGIN_DISABLED_ERROR);
        }

        String name =userInfo.getName();

        if(StringUtils.isEmpty(name)){
            name = userInfo.getNickName();
        }

        if(StringUtils.isEmpty(name)){
            name = userInfo.getPhone();
        }

        String token = JwtHelper.createToken(userInfo.getId(), name);

        Map<String,Object> resultMap
                = new HashMap<>();
        resultMap.put("token",token);
        resultMap.put("name",name);
        return resultMap;
    }

    @Override
    public UserInfo getUserInfoByOpenid(String openId) {

        return baseMapper.selectOne(new QueryWrapper<UserInfo>().eq("openid",openId));
    }

    @Override
    public void userAuth(String token, UserAuthVo userAuthVo) {

        String userId = JwtHelper.getUserId(token);

        UserInfo userInfo = baseMapper.selectById(userId);

        userInfo.setName(userAuthVo.getName());
        userInfo.setCertificatesType(userAuthVo.getCertificatesType());
        userInfo.setCertificatesNo(userAuthVo.getCertificatesNo());
        userInfo.setCertificatesUrl(userAuthVo.getCertificatesUrl());
        userInfo.setAuthStatus(1);

        baseMapper.updateById(userInfo);
    }

    @Override
    public IPage<UserInfo> pageUserInfo(Page<UserInfo> userInfoPage, UserInfoQueryVo queryVo) {
        QueryWrapper<UserInfo> userInfoQueryWrapper = new QueryWrapper<>();

        Integer authStatus = queryVo.getAuthStatus();
        Integer status = queryVo.getStatus();
        String keyword = queryVo.getKeyword();
        String timeBegin = queryVo.getCreateTimeBegin();
        String timeEnd = queryVo.getCreateTimeEnd();

        if(!StringUtils.isEmpty(authStatus)){
            userInfoQueryWrapper.eq("auth_status",authStatus);
        }

        if(!StringUtils.isEmpty(status)){
            userInfoQueryWrapper.eq("status",status);
        }

        if(!StringUtils.isEmpty(keyword)){
            userInfoQueryWrapper.like("name",keyword);
        }

        if(!StringUtils.isEmpty(timeBegin)){
            userInfoQueryWrapper.ge("gmt_create",timeBegin);
        }

        if(!StringUtils.isEmpty(timeEnd)){
            userInfoQueryWrapper.le("gmt_create",timeEnd);
        }

        IPage<UserInfo> userInfoIPage = baseMapper.selectPage(userInfoPage, userInfoQueryWrapper);

        userInfoIPage.getRecords().forEach(this::packageUserInfo);

        return userInfoIPage;
    }

    @Override
    public Map<String, Object> showUserInfo(String userId) {
        Map<String,Object> resultMap = new HashMap<>();

        UserInfo userInfo = baseMapper.selectById(userId);

        List<Patient> allPatient =
                patientService.findAllPatient(userId);
        allPatient.forEach(patient -> {
            patientService.packParam(patient);
        });

        resultMap.put("patientList",allPatient);
        resultMap.put("userInfo",userInfo);

        return resultMap;
    }

    @Override
    public void approve(String userId, Integer status) {

        if(status == 2 || status ==-1){
            UserInfo userInfo = new UserInfo();
            userInfo.setId(userId);
            userInfo.setAuthStatus(status);
            baseMapper.updateById(userInfo);

        }
    }

    private void packageUserInfo(UserInfo userInfo) {
        //处理认证状态编码
        userInfo.getParam().put("authStatusString", AuthStatusEnum.getStatusNameByStatus(userInfo.getAuthStatus()));
        //处理用户状态 0  1
        String statusString = userInfo.getStatus() == 0 ?"锁定" : "正常";
        userInfo.getParam().put("statusString",statusString);
    }

}
